<template>
    <div id="containerMain" ref="containerMain" class="commm-player-main" :style = "container.style1" @click="container.click()"
         @mouseover="container.mouseOver()" @mouseleave="container.mouseLeave()">
      <div v-show="!loading" class="videoBox_wt" @mouseenter="showBar" @mouseleave = "hideBar">
        <video :id="videoId"
               :ref="videoId"
               class="videoPlayer_wt"
               autoplay>
        </video>
        <!--                 :style="{marginLeft: iel.marginLeft,cursor:iel.cursor}">-->
        <div class="controlBar_wt" :style="container.sizeprop.barStyle">
          <div class="controlBar1_wt">
            <div class="btn-left_wt" style="height: 100%">
              <i class="btn-i_wt" :title="ph.play" v-show="playControls.status==0 || playControls.status==3" @click="rePlay"
              :style="playControls.btn.cursorStyle">
                <Icon type="md-play" :size="container.sizeprop.iconSize" :color="playControls.btn.color"/></i>
              <i class="btn-i_wt" :title="ph.play" v-show="playControls.status==2" @click="rePlay"
                 :style="playControls.btn.cursorStyle">
                <Icon type="md-play" :size="container.sizeprop.iconSize" :color="playControls.btn.color"/></i>
              <i class="btn-i_wt"  :title="ph.stop" v-show="playControls.status==1" @click="stop">
                <Icon type="md-square" :size="container.sizeprop.iconSize"/></i>
              <i class="btn-i_wt"  :title="ph.pause" v-show="playControls.status==1" @click="pause">
                <Icon type="md-pause" :size="container.sizeprop.iconSize" /></i>
              <span :style="container.sizeprop.currentTimeSpanStyle">{{currentTime}}</span>
<!--              <span :style="{marginLeft:'20px',fontSize:'30px'}">{{currentTime}}</span>-->

              <i class="btn-i_wt" :title="ph.openAudio" v-show="playControls.audio==0 && playControls.status==1" @click="openAudio">
                <Icon type="md-volume-off" :size="container.sizeprop.iconSize"/></i>
              <i class="btn-i_wt" :title="ph.closeAudio" v-show="playControls.audio==1 && playControls.status==1" @click="closeAudio">
                <Icon type="md-volume-up" :size="container.sizeprop.iconSize"/></i>
              <i class="btn-i_wt" :title="ph.volume" v-show="playControls.audio==1 && playControls.status==1" @click="volAdjust">
                <Icon type="md-funnel" :size="container.sizeprop.iconSize"/></i>

              <Slider :title="ph.ajdustValume" v-model="volume" :max="10" :min="1" style="width:60px;"
                      v-show="playControls.isVolAdjust" @on-change="volumeChange"> </Slider>

<!--              <div class="progressVol_wt" v-show="playControls.isVolAdjust">
&lt;!&ndash;                <el-slider :max="10" :min="1" v-model="volume"  vertical  height="100px" @change="volumeChange"> </el-slider>&ndash;&gt;
&lt;!&ndash;                <CustomSlider></CustomSlider>&ndash;&gt;

              </div>-->

              <div :style="container.sizeprop.deviceSpanStyle" >
                <span > {{deviceName}} </span>
              </div>

            </div>
            <div class="btn-right_wt" style="height: 100%">
              <i class="btn-i_wt" style="margin-right: 20px" title="Test" v-show="1===0">
                <Icon type="md-aperture" :size="container.sizeprop.iconSize" @click="testEldialog"/></i>

                <i class="btn-i_wt" style="margin-right: 20px" :title="ph.fullScreen" v-show="!playControls.isFullScreen">
                <Icon type="md-qr-scanner" :size="container.sizeprop.iconSize" @click="fullScren"/></i>
              <i class="btn-i_wt" style="margin-right: 20px" :title="ph.cancelFullScreen" v-show="playControls.isFullScreen">
                <Icon type="md-contract" :size="container.sizeprop.iconSize" @click="cancelFullScren"/></i>
              <i class="btn-i_wt" style="margin-right: 20px" :title="ph.startTheIntercom" v-show="!playControls.isTalk && playControls.status==1">
                <Icon type="md-mic-off" :size="container.sizeprop.iconSize" @click="talk"/></i>
              <i class="btn-i_wt" style="margin-right: 20px" :title="ph.endTheIntercom" v-show="playControls.isTalk && playControls.status==1">
                <Icon type="md-mic" :size="container.sizeprop.iconSize" color="green" @click="stopTalk"/></i>

              <canvas id="talkCanvas" ref="talkCanvas" style="width: 50px;height: 100%" v-show="playControls.isTalk && playControls.status==1"></canvas>
            </div>
          </div>

        </div>
      </div>
      <div v-show="loading" style="width: 100%;height: 100%;display: flex;justify-content: center;align-items: center;background-color:#0c0c0c">
        <Spin size="large" ></Spin>
      </div>

      <GbTalkPlayer ref="gbTalkPlayer"    @close-talk="stopTalk" ></GbTalkPlayer>
      <GbTalkUnDialogPlayer ref="gbTalkUnDialogPlayer"></GbTalkUnDialogPlayer>

<!--      <el-dialog title="国标对讲" top="30%" :modal="false" :close-on-click-modal="false" :visible.sync="showelDialog" >
        <div style="height: 100px;width: 100%;background-color: #0c0c0c">

        </div>
      </el-dialog>-->

    </div>
</template>
<script>
import GbTalkPlayer from "@/view/Home/component/GbTalkPlayer.vue";
import GbTalkUnDialogPlayer from "@/view/Home/component/GbTalkUnDialogPlayer.vue";
import CustomSlider from '@/components/topnav/CustomSlider.vue'

/*import PlayerWaterMark from "@/view/Home/component/PlayerWaterMark";
import PlayerWaterMark1 from "@/view/Home/component/PlayerWaterMark1";
import PlayerWaterMark2 from "@/view/Home/component/PlayerWaterMark2";*/
import Device from "@/api/Device";
import Apiproxy from "@/api/Apiproxy";
import {logout} from "@/api/login";
import config from '@/config'
import {apiResult} from "@/libs/util";
export default {
  name:"RtcWithTalkPlayer",
  components:{GbTalkPlayer,CustomSlider,GbTalkUnDialogPlayer},
  props:{
    videoId:{type: String, default: "webrtcPlayer-demo"},
    active:{type:Boolean, default: false },
    id:{type:Number, default:-1 },
    autoReplay:{type:Boolean,default:true}, //如果断网自动重播
    showCustomBar:{type:Boolean,default:true}, //是否显示自定义面板
    muted:{type:Boolean,default:true} //是否静音
  },
  computed: {
    ph() {
      return {
        play: this.$t('play'),
        stop: this.$t('stop'),
        pause: this.$t('pause'),
        closeAudio: this.$t('close_audio'),
        openAudio: this.$t('open_audio'),
        volume: this.$t('volume'),
        ajdustValume: this.$t('adjust_volume'),
        startTheIntercom: this.$t('start_the_intercom'),
        endTheIntercom: this.$t('end_the_intercom'),
        fullScreen: this.$t('full_screen'),
        cancelFullScreen: this.$t('cancel_full_screen'),
        httpsProtocolSupportsIntercom: this.$t('only_https_protocol_supports_intercom'),
      }
    },
  },
  watch: {
    muted(n,o){
      console.log("RtcWithTalkPlayer: watch.muted: %o",n)
      if (n){
        this.closeAudio(); //静音
      }else{
        this.openAudio() //关静音
      }
    }
  },
  data() {
    return {
      //showelDialog:false,
      loading: false,
      hp: '10px', wp: '10px',
      ielMarginLeft: "10px",
      ielColor: "#999999",
      ielCursor: "auto",
      level: 1, //水印大小级别 1最大
      iel: {
        marginLeft: "30px",
        color: "#999999",
        cursor: "auto",
      },
      api: new Device(),
      volume: 5,
      //containerMainId:"containerMainId100001",
      currentTime: "00:00:00",
      playControls: {
        status: 0,//0停止 1 播放 2 暂停, 3 断开
        audio: 0, //0声音关，1声音开
        isVolAdjust: false,
        isFullScreen: false,
        isTalk: false,
        playUrl: null,
        btn: {
          color: "#999999",
          cursorStyle: "cursor: auto",
        }
      },

      /*video 标签 包括 鼠标事件的处理*/
      container: {
        mouseMove: 0,
        activeState: 0,
        sizeprop: {
          iconSize: 18, //圉标大小
          fontSize: 18, //字体大小
          marginLeft: '5px',
          controlBar_wt: '55px',
          deviceSpanStyle: {marginLeft: '30px', fontSize: '36px'},
          currentTimeSpanStyle: {marginLeft: '20px', fontSize: '36px'},
          barStyle: {display: 'none', height: '55px'},
        },
        style1: "border:1px solid #011a2f",
        moveInStyle: 'border:1px solid #063ffc',//移入时边框
        activeStyle: 'border:1px solid #FF0000', //选中时的边框
        unActiveStyle: 'border:1px solid #032a52', //没选中时的边框
        /**
         * 计算宽高
         * h 高，w 宽
         */
        clacStyle(h, w) {

        },
        click: () => {
          this.container.mouseMove = 0;
          this.$emit('on-select-active', !this.container.activeState, this.id)
        },
        mouseOver: () => {
          this.container.mouseMove = 1;
          this.container.hoverClass();
        },
        mouseLeave: () => {
          this.container.mouseMove = 2;
          this.container.hoverClass();
        },
        hoverClass: () => {
          //console.log(">>>>> PlayerContainer.hoverClass: mouseMove=%o;activeState=%o;active=%o",this.mouseMove,this.activeState,this.active);
          if (this.container.activeState) {
            this.container.style1 = this.container.activeStyle;
          } else {
            if (this.container.mouseMove === 1) {
              this.container.style1 = this.container.moveInStyle;
            } else {
              this.container.style1 = this.container.unActiveStyle;
            }
          }
        },
      },
      deviceId: null,
      channelId: null,
      deviceName: "Cammpro",
      protocol: "rtc",
      //timer: null,
      videoElement: null,
      delayTimer: null,
      //mediaHost: null,  //https://default.zlmediakit.com
      isHttps: false,
      //gbServerId: null,
      playTime: {
        stopTime: null,
        playTimeout: 18000, //从国标服务器出来，多长时间不拉流则断流，断流了就要重新invit 否则直接play()
        replayTimer: null,//重刷定时器
        replayCount: 0, //重刷次数
        replayInterval: 10000, //第一轮重连频率毫秒
        repleyMax: 3, //第一轮重连频数
        replayInterval2: 30000, //第二轮重连频率毫秒
        repleyMax2: 3 //第二轮重连频数
      },
      videoPlayer: null,
      errCallback: null,
      recorder:null,
      recordCallback:null,
    }
  },
  methods: {
    testEldialog() {
      this.showelDialog = true;
    },
    addVideoEvent(e, evtCallback) {
      //console.log("videoElement=%o,e=%o, evtCallback=%o",this.videoElement,e,evtCallback);
      this.videoElement.addEventListener(e, () => {
        if (e != "timeupdate") {
          //console.log("事件==>%o:%o",(new Date()).getTime(),e)
        }
        if (!!evtCallback) {
          evtCallback(e);
        }
      })
    },
    cancelFullScren() {
      this.videoElement.webkitExitFullScreen();
      this.playControls.isFullScreen = false;
    },
    /**
     * 关闭所有定时器
     */
    clearAllTimer() {
      this.clearTimer(this.delayTimer);
      this.clearTimer(this.playTime.replayTimer);
    },
    /**
     * 关闭某定时器
     */
    clearTimer(timer) {
      if (!!timer) {
        clearInterval(timer);
        timer = null;
      }
    },
    closeAudio() {
      if (!!this.videoElement) {
        this.videoElement.muted = true;
      }

      this.playControls.audio = 0;
      this.playControls.isVolAdjust = false;
    },
    /**
     * 第定时器，第二次定时比第一次更长
     */
    createReplayTimer(timer) {
      const _this = this;
      let interval = 0;
      let maxTimer = 0;
      console.log(this.playTime);
      if (timer == 1) {
        interval = this.playTime.replayInterval;
        maxTimer = this.playTime.repleyMax;
      } else {
        interval = this.playTime.replayInterval2;
        maxTimer = this.playTime.repleyMax2 + this.playTime.repleyMax;
      }
      _this.rePlay();
      this.playTime.replayTimer = setInterval(() => {
        _this.playTime.replayCount++;
        if (_this.playTime.replayCount > maxTimer) {
          clearInterval(_this.playTime.replayTimer);
          if (timer == 2) {
            console.log("设备 %o, 重连 %o 次不成功，判定为已离线", _this.deviceName, maxTimer);
            _this.stop();
          } else {
            _this.playTime.replayCount--;
            _this.createReplayTimer(2);
          }
          return;
        }
        console.log("设备 %o, 第 %o 次重连", _this.deviceName, _this.playTime.replayCount);
        _this.rePlay();
      }, interval)
    },
    fullScren() {
      this.videoElement.webkitEnterFullScreen();
      this.playControls.isFullScreen = true;
    },

    getPlayUrl() {
      const _this = this;
      return new Promise((resolve, reject) => {
        this.api.playStart(this.deviceId, this.channelId).then(res => {
          apiResult(res.data,true,result=>{
            if (!!res.data.data[_this.protocol]) {
              const playUrl = result.data[this.protocol];
              console.log(">>>>> RtcWithTalkPlayer.playUrl: %o",playUrl)
              //const originUrl = new URL(playUrl);
              //console.log("originUrl=%o;protocol=%o;host=%o;pathname=%o;search=%o", playUrl, originUrl.protocol, originUrl.host, originUrl.pathname, originUrl.search)
              //console.log("searchParams=%o", originUrl.searchParams)
              //console.log(originUrl.search.split("?")[1].split("&")[1].split("=")[1].split("_"));
              //https://192.168.0.129:8443/index/api/webrtc?app=rtp&stream=44010200492000000020_44030000492000000020&type=play
              this.playControls.playUrl = this.api.getPlayUrl(playUrl);
              console.log(">>>>> RtcWithTalkPlayer.playControls.playUrl: %o",this.playControls.playUrl)
              resolve()
            }
          },err=>{
            //console.log("error：%o", res.data.msg);
            if (!!_this.errCallback) {
              _this.errCallback(err.msg);
            }
          })
          /*if (res.data.code == 0) {
            console.log("播放地址：%o", res.data.data);

            if (!!res.data.data[_this.protocol]) {
              const playUrl = res.data.data[this.protocol];
              const originUrl = new URL(playUrl);
              console.log("originUrl=%o;protocol=%o;host=%o;pathname=%o;search=%o", playUrl, originUrl.protocol, originUrl.host, originUrl.pathname, originUrl.search)

              console.log("searchParams=%o", originUrl.searchParams)
              console.log(originUrl.search.split("?")[1].split("&")[1].split("=")[1].split("_"));
              //https://192.168.0.129:8443/index/api/webrtc?app=rtp&stream=44010200492000000020_44030000492000000020&type=play

              this.playControls.playUrl = this.api.getPlayUrl(playUrl);

              /!*                //生产环境和开发不一样
            if (process.env.NODE_ENV == "production") {
              //生产环境,通过nginx代理，本地IP:port+/mcpro/webrtc/
              const docUrl = new URL(document.location);
              console.log(">>>>>> document.location=%o",docUrl);
              console.log(">>>>>> protocol=%o",docUrl.protocol); // 输出 "https:"
              console.log(">>>>>> hostname=%o",docUrl.hostname); // 输出 "www.example.com"
              console.log(">>>>>> port=%o",docUrl.port); // 输出 ""（没有指定端口）
              let originUrl = docUrl.protocol + "//" + docUrl.hostname
              console.log(">>>>>> originUrl=%o",originUrl);
              if (!!docUrl.port){
                originUrl = originUrl + ":" + docUrl.port;
              }
              originUrl = originUrl + "/mcpro/webrtc";
              this.mediaHost = originUrl;
              //originUrl = originUrl + !!docUrl.port?":" + docUrl.port:"";
              console.log(">>>>>> originUrl=%o",originUrl);
              originUrl = originUrl + playUrl.substring(playUrl.indexOf("/index/api/webrtc?"));
              console.log(">>>>>> 生产环境 播放地址：%o",originUrl);
              this.playControls.playUrl = originUrl;
            }else{
              //开发环境
              this.playControls.playUrl=playUrl.replace(":443/", ":8443/")
              console.log(">>>>>> 开发环境 播放地址：%o",this.playControls.playUrl);
            }*!/
              /!*                if (!!this.mediaHost){
              if (this.mediaHost[this.mediaHost.length-1] === "/"){
                url = this.mediaHost.substring(0,this.mediaHost.length-1) + url;
              }else{
                url = this.mediaHost + url;
              }
            }
            console.log(">>>>>> url=%O",url);*!/
              //this.playControls.playUrl=url.replace(":443/", ":8443/")
              //this.playControls.playUrl = res.data.data[this.protocol];

              resolve()
            }
          } else {
            console.log("错误：%o", res.data.msg);
            console.log("获取播放地址错误，请确认设备是否在线");
            if (!!_this.errCallback) {
              _this.errCallback(res.data.msg);
            }

          }*/
        }).catch(err => {
          reject(err)
        })
      });
    },
    hideBar() {
      this.container.sizeprop.barStyle.display = 'none';
    },
    isStopTimeOut() {
      return (new Date()).getTime() - this.playTime.stopTime > this.playTime.playTimeout;
    },
    isPlaying() {
      return this.playControls.status === 1;
    },
    mainClick() {
      this.mouseMove = 0;
      this.$emit('on-select-active', !this.activeState, this.id)
    },
    openAudio() {
      if (this.playControls.status != 1) {
        return;
      }
      if (!!this.videoElement) {
        this.videoElement.muted = false;
      }
      this.playControls.audio = 1;
    },
    openDialog(deviceId, channelId, host, deviceName, errCallback) {
      //console.log(errCallback);
      this.errCallback = errCallback;
      this.loading = true;
      this.playControls.isTalk = false;
      this.deviceName = deviceName;
      //this.mediaHost = host;
      this.deviceId = deviceId;
      this.channelId = channelId;
      this.playControls.btn.color = "#ffffff";
      this.playControls.btn.cursorStyle = "cursor: pointer";
      //console.log("openDialog");
      this.stop()
      //初始时间
      this.playTime.stopTime = new Date().getTime() - this.playTime.playTimeout - 1000;
      this.getPlayUrl().then(() => {
        this.loading = false;
        this.play();
      })

      if (this.muted){
        this.closeAudio()
      }else{
        this.openAudio();
      }
    },

    pause() {
      if (!!this.videoElement) {
        this.videoElement.pause();
      }
      this.playControls.status = 2;
      this.playTime.stopTime = new Date().getTime();
      console.log("pause()=>stopTime: %o ", this.playTime.stopTime);
    },
    play() {
      //console.log("play():status=%o;videoPlayer=%o",this.playControls.status,this.videoPlayer)
      if (this.playControls.status === 3) {
        this.playInit();
        return;
      }

      if (!this.videoPlayer) {
        this.playInit();
      }
      this.videoElement.play();
    },

    /**
     * 播放并录像
     * videoUrl 播放地址
     * recordCallback 录像回调
     */
    recordUrl(videoUrl,recordCallback){
      console.log(">>>>>> recordUrl: %o", recordCallback)
      this.recordCallback = recordCallback;
      this.stop();
      this.playControls.playUrl = videoUrl;
      if (!this.videoPlayer) {
        this.playInit();
      }
      this.videoElement.play();
    },
    /**
     * 播放指定的 URL
     */
    playByUrl(videoUrl) {
      this.recordCallback = null;
      this.stop();
      this.playControls.playUrl = videoUrl;
      if (!this.videoPlayer) {
        this.playInit();
      }
      this.videoElement.play();
      //console.log(videoUrl);
    },
    playInit() {
      this.videoPlayer = null;
      const _this = this;
      //console.log("playUrl=%o",_this.playControls.playUrl);
      this.videoPlayer = new ZLMRTCClient.Endpoint({
        element: document.getElementById(this.videoId),// video 标签
        debug: false,// 是否打印日志
        zlmsdpUrl: _this.playControls.playUrl,//流地址
        simulecast: false,
        useCamera: false,
        audioEnable: true,
        videoEnable: true,
        recvOnly: true,
      })
      //协商出错
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ICE_CANDIDATE_ERROR, (e) => {// ICE 协商出错
        console.error('ICE 协商出错: %o', e)
        //this.eventcallbacK("ICE ERROR", "ICE 协商出错")
      });

      //播放成功
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_REMOTE_STREAMS, (e) => {//获取到了远端流，可以播放
        console.log('播放成功: %o', e)
        console.log('>>>>>> 是否在录像: %o，%o', _this.recordCallback,_this.videoElement)
        //是否在录像
        if (!!_this.recordCallback){
          _this.recordCallback(_this.videoElement);
        }

        if (!!_this.delayTimer) {
          clearInterval(_this.delayTimer)
          _this.delayTimer = null;
        }



        //定时取状态
        _this.delayTimer = setInterval(() => {
          if (!!_this.videoElement) {
            //当前播放时间
            _this.currentTime = _this.timeFormat(_this.videoElement.currentTime)
            this.$emit('playCurrentTime', _this.currentTime);
            //console.log(_this.currentTime);
            //console.log("播放的时间: %o", _this.currentTime);
            /*              console.log("是否暂停播放: %o",_this.vedioElement.paused);
          console.log("视频的总时长: %o",_this.vedioElement.duration);
          console.log("音量大小: %o",_this.vedioElement.volume);
          console.log("全屏显示: %o",_this.vedioElement.webkitDisplayingFullscreen);
          console.log("已经加载的缓冲范围: %o",_this.vedioElement.buffered);
          console.log("已经播放的时间范围: %o",_this.vedioElement.played);
          console.log("URL地址: %o",_this.vedioElement.currentSrc);*/
          }
        }, 1000)

        // 清除断开重刷
        if (!!_this.playTime.replayTimer) {
          clearInterval(_this.playTime.replayTimer)
        }

        _this.playControls.status = 1;
      });

      //交换失败
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_OFFER_ANWSER_EXCHANGE_FAILED, (e) => {// offer anwser 交换失败
        console.error('offer anwser 交换失败: %o', e)
        //this.eventcallbacK("OFFER ANSWER ERROR ", "offer anwser 交换失败")
        if (e.code == -400 && e.msg == "流不存在") {
          console.log("流不存在")
          setTimeout(() => {
            this.videoPlayer.close();
            this.rePlay()
          }, 100)
        }
      });

      //获取到了本地流
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_LOCAL_STREAM, (s) => {// 获取到了本地流
        console.log("获取到了本地流: %o", s)
        // document.getElementById('selfVideo').srcObject=s;
        //this.eventcallbacK("LOCAL STREAM", "获取到了本地流")
      });
      //获取本地流失败
      this.videoPlayer.on(ZLMRTCClient.Events.CAPTURE_STREAM_FAILED, function (s) {// 获取本地流失败
        console.log('获取本地流失败')
      });

      //当前状态==>
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_CONNECTION_STATE_CHANGE, function (state) {// RTC 状态变化 ,详情参考 https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/connectionState
        console.log('当前状态==>', state)
        if (state == 'disconnected') {
          //是否在下载
          if (!!_this.recorder){
            _this.recorder.stop();
            _this.recorder=null;
          }

          //设备断开几秒后才捕让捉到此事件
          _this.playTime.stopTime = new Date().getTime() - 3 * 1000;
          _this.playControls.status = 3;
          //断开自动定时重刷
          _this.playTime.replayCount = 0;
          if (_this.autoReplay) {
            //断网自动重连
            _this.createReplayTimer(1);
          }


          /*            _this.playTime.replayTimer = setInterval(()=>{
          _this.playTime.replayCount++;
          if (_this.playTime.replayCount > _this.playTime.repleyMax){
            console.log("设备 %o, 重连 %o 次不成功，判定为已离线",_this.deviceName,_this.playTime.repleyMax);
            _this.stop();
            clearInterval(_this.playTime.replayTimer);
            return;
          }
          console.log("设备 %o, 第 %o 次重连",_this.deviceName,_this.playTime.replayCount);
          _this.rePlay();
        }, this.replayTimer.replayInterval)*/
        }
      });

      //rtc datachannel 打开
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_OPEN, function (event) {
        console.log('rtc datachannel 打开 :', event)
      });

      //rtc datachannel 消息
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_MSG, function (event) {
        console.log('rtc datachannel 消息 :', event.data)
        document.getElementById('msgrecv').value = event.data
      });
      //rtc datachannel 错误
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_ERR, function (event) {
        console.log('rtc datachannel 错误 :', event)
      });
      //rtc datachannel 关闭
      this.videoPlayer.on(ZLMRTCClient.Events.WEBRTC_ON_DATA_CHANNEL_CLOSE, function (event) {
        console.log('rtc datachannel 关闭 :', event)
      });
    },
    rePlay() {
      if (this.playControls.status == 3) {
        //rtc 已经断开就必须重连
        this.getPlayUrl().then(() => {
          this.play();
        })
      } else {
        if (this.isStopTimeOut() || !this.videoElement.srcObject) {
          this.getPlayUrl().then(() => {
            this.play();
          })
        } else {
          this.play();
        }
      }


    },
    setActive(active) {
      this.container.activeState = active;
      this.container.mouseMove = 0;
      this.container.hoverClass();
    },
    showBar() {
      //console.log("video: height=%o",this.videoElement);
      if (this.showCustomBar)
        this.container.sizeprop.barStyle.display = 'block';
    },

    stop() {
      this.$refs.gbTalkUnDialogPlayer.close();
      this.playTime.stopTime = new Date().getTime();
      //console.log("stop()=>stopTime: %o ",this.playTime.stopTime);
      if (!!this.videoPlayer) {
        this.videoPlayer.close();
        this.videoPlayer = null;
        this.videoElement = document.getElementById(this.videoId);
        if (!!this.videoElement) {
          this.videoElement.srcObject = null;
          this.videoElement.load();
        }

      }
      this.clearAllTimer();
      this.playControls.status = 0;
    },
    stopTalk() {
      this.$refs.gbTalkUnDialogPlayer.stop();
      this.$Message.success(this.$t('end_the_intercom'));
      this.playControls.isTalk = false;
    },

    talk() {
      if ('https:' !== document.location.protocol) {
        //this.$Message.error(this.$t('only_https_protocol_supports_intercom'));
        this.$Message.error(this.ph.httpsProtocolSupportsIntercom);
        return;
      }
      this.openAudio();
      console.log(this.$refs.gbTalkUnDialogPlayer);
      const msg = this.$Message.loading({content: this.$t('wait_for_connect_device'),duration: 20});

      this.$refs.gbTalkUnDialogPlayer.openDialog(this.deviceId, this.channelId,this.$refs.talkCanvas,
        result=>{
            if (result.code === -1){
              this.$Message.error(result.msg);
              this.stopTalk();
              setTimeout(msg, 100); //关闭正加载条
              this.playControls.isTalk = false;
            }else if (result.code === 0){
              this.$Message.success(result.msg);
              this.stopTalk();
              setTimeout(msg, 100); //关闭正加载条
              this.playControls.isTalk = false;
            } if (result.code === 1) {
              setTimeout(msg, 100); //关闭正加载条
              this.$Message.success(result.msg);
              this.playControls.isTalk = true;
            }
          }

      );

/*          this.$refs.gbTalkPlayer.openDialog(this.deviceId, this.channelId, (result) => {
        if (!!result) {
          if (result.code === 0) {
            this.playControls.isTalk = true
          } else {
            this.$Message.error(result.msg)
            this.playControls.isTalk = false;
          }
        }
      },this.$refs.talkCanvas)*/
    },

    //视频时长格式化
    timeFormat(time) {
      let hour = Math.floor(time / 3600),
        minute = Math.floor((time % 3600) / 60),
        second = Math.floor(time % 60);
      hour = hour < 10 ? "0" + hour : hour;
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return `${hour}:${minute}:${second}`;
    },
    volAdjust() {
      this.playControls.isVolAdjust = !this.playControls.isVolAdjust;
    },

    volumeChange(value) {
      if (!!this.videoElement) {
        this.videoElement.volume = this.volume / 10;
      }
    },
    /**
     * 录像
     */
    recording(){
      const _this = this;
      if (!!this.videoElement) {
        console.log(">>>>>> recording......")
        const video = this.videoElement;
        //console.log("RtcWithTalkPlayer.recording: video=%o",video)
        //取得stream
        video.captureStream = video.captureStream || video.mozCaptureStream;
        const mediaStream =  video.captureStream();
        //判断是否支持 哪一种webm
        const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264")
          ? "video/webm;codecs=h264"
          : "video/webm";
        //console.log(mime);

        let recorder = new MediaRecorder(mediaStream,{ mimeType: mime });
        // 音视频 数组
        let chunks = [];
        // 录像事件： 有数据时就加入数组
        recorder.ondataavailable = (event) => {
          console.log(event.data);
          chunks.push(event.data);
        }

        //停止事件
        recorder.onstop=(stream)=>{
          console.log(">>>>>> record stop")
          // 获取视频源
          const blob = new Blob(chunks, { type: chunks[0].type });
          //创建URL
          const url = URL.createObjectURL(blob);
          // 创建下载链接
          const downloadLink = document.createElement("a");
          downloadLink.href = url;
          downloadLink.download = "video.mp4";
          // 添加链接到界面
          document.body.appendChild(downloadLink);
          // 触发下载
          downloadLink.click();
          // 清理界面
          document.body.removeChild(downloadLink);

          //a.click();
          //document.removeElement(a)
        }
        if (!!_this.recorder)
           _this.recorder.start();

        // 获取视频源
        //let videoBlob = new Blob([video.msSrcObject || video.src], { type: 'video/mp4' });
        //console.log("RtcWithTalkPlayer.downloadtest: videoBlob=%o",videoBlob)

        // 创建URL
        //var url = URL.createObjectURL(videoBlob);
        //console.log("RtcWithTalkPlayer.downloadtest: url=%o",url)
        //return;

        // 创建下载链接
/*            var downloadLink = document.createElement("a");
        downloadLink.href = url;
        downloadLink.download = "downloadedVideo.mp4"; // 指定下载文件名

        // 添加链接到界面
        document.body.appendChild(downloadLink);

        // 触发下载
        downloadLink.click();

        // 清理界面
        document.body.removeChild(downloadLink);*/
      }

      //var video = document.getElementById(videoElement);
    }
  },
  beforeDestroy() {
    console.log("************* RtcWithTalkPlayer.beforeDestroy()");
    this.stop();
    this.clearAllTimer();
  },
  resizeEvent() {

  },
  mounted() {
    const _this = this;
    this.$nextTick(() => {

      this.videoElement = document.getElementById(_this.videoId);
      console.log("********* videoId=%o,videoElement=%o", _this.videoId, this.videoElement);
      if (!!this.videoElement) {
        this.videoElement.volume = this.volume / 10;
        this.videoElement.muted = true;
      }
      this.isHttps = 'https:' === document.location.protocol;
      this.protocol = this.isHttps ? "rtcs" : "rtc";
      //this.protocol = "rtc";
      this.playControls.audio = false;

      this.addVideoEvent("loadstart");   //客户端开始请求数据
      this.addVideoEvent("progress");   //客户端正在请求数据
      this.addVideoEvent("suspend");   //延迟下载
      this.addVideoEvent("abort");   //客户端主动终止下载（不是因为错误引起），
      this.addVideoEvent("error");   //请求数据时遇到错误
      this.addVideoEvent("stalled", (e) => {
        console.log("网速失速")
      });   //网速失速
      this.addVideoEvent("play");   //play()和autoplay开始播放时触发
      this.addVideoEvent("pause", (e) => {
      });   //pause()触发
      this.addVideoEvent("loadedmetadata", (e) => {
        console.log("【loadedmetadata】")
      });   //成功获取资源长度
      this.addVideoEvent("loadeddata");   //
      this.addVideoEvent("playing", (e) => {
        _this.playControls.status = 1
      });   //开始回放
      this.addVideoEvent("canplay");   //pause()触发
      this.addVideoEvent("canplaythrough");   //可以播放，歌曲全部加载完毕
      this.addVideoEvent("seeking");   //pause()触发
      this.addVideoEvent("seeked");   //寻找完毕
      this.addVideoEvent("timeupdate");   //播放时间改变
      this.addVideoEvent("ended");   //播放结束
      this.addVideoEvent("ratechange");   //播放结束
      this.addVideoEvent("durationchange");   //资源长度改变
      this.addVideoEvent("volumechange");   //播放结束
      this.addVideoEvent("ended");   //播放结束

      this.deviceName = "CMVS";
      //console.log("location.protocol=%o,isHttps=%o,protocol=%o",document.location.protocol,this.isHttps,this.protocol,);
    })
    // 监听元素的尺寸变化
    const element = this.$refs.containerMain;// document.getElementById('containerMain');
    //const element = document.getElementById('containerMain');
    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
        const {width, height} = entry.contentRect;
        //console.log(`********* resize>>>> 宽度: ${width}px, 高度: ${height}px`);
        this.hp = height;
        this.wp = width;
        if (width > 1800) {
          this.level = 1;
          _this.container.sizeprop.barStyle.height = '55px';
          _this.container.sizeprop.iconSize = 36;
          _this.container.sizeprop.deviceSpanStyle = {marginLeft: '36px', fontSize: '36px'};
          _this.container.sizeprop.currentTimeSpanStyle = {marginLeft: '30px', fontSize: '36px'};
        } else if (width > 1000) {
          this.level = 1;
          _this.container.sizeprop.barStyle.height = '55px';
          _this.container.sizeprop.iconSize = 28;
          _this.container.sizeprop.deviceSpanStyle = {marginLeft: '28px', fontSize: '28px'};
          _this.container.sizeprop.currentTimeSpanStyle = {marginLeft: '28px', fontSize: '28px'};
        } else if (width > 500) {
          this.level = 2;
          _this.container.sizeprop.barStyle.height = '45px';
          _this.container.sizeprop.iconSize = 20;
          _this.container.sizeprop.deviceSpanStyle = {marginLeft: '20px', fontSize: '20px'};
          _this.container.sizeprop.currentTimeSpanStyle = {marginLeft: '20px', fontSize: '20px'};
        } else if (width > 300) {
          this.level = 3;
          _this.container.sizeprop.barStyle.height = '35px';
          _this.container.sizeprop.iconSize = 16;
          _this.container.sizeprop.deviceSpanStyle = {marginLeft: '25px', fontSize: '15px'};
          _this.container.sizeprop.currentTimeSpanStyle = {marginLeft: '15px', fontSize: '15px'};
        } else {
          this.level = 3;
          _this.container.sizeprop.barStyle.height = '20px';
          _this.container.sizeprop.iconSize = 8;
          _this.container.sizeprop.deviceSpanStyle = {marginLeft: '3px', fontSize: '3px'};
          _this.container.sizeprop.currentTimeSpanStyle = {marginLeft: '3px', fontSize: '8px'};
        }


        //console.log('********* currentTimeSpanStyle = %o',this.container.sizeprop.currentTimeSpanStyle);
        /*          _this.container.sizeprop.iconSize
        mouseMove:0,
          activeState:0,
          sizeprop:{
            iconSize: 18, //圉标大小
            fontSize: 18, //字体大小
            marginLeft: '5px',
            controlBar_wt: '55px',
            deviceSpanStyle:'font-size: 14px',
            currentTimeSpanStyle:'font-size: 14px'
        },*/


        // 在这里执行您的逻辑，响应尺寸变化
      }
    });
    resizeObserver.observe(element);


  }
}
</script>
<style lang="less">
@import "Player";
.videoBox_wt{
  position: relative;
  width: 100%;
  height:100%;
  background-color: rgb(3, 17, 31);
  //border:1px solid #011a2f;
  //background-color: #0c0c0c;
  .videoPlayer_wt{
    width: 100%;
    height: 100%;
    background-color: #0c0c0c;
  }
  .controlBar_wt {
    /*border-top-right-radius: 5px;*/
    border-radius: 5px;
    width: 90%;
    height: 55px;
    position: absolute;
    bottom: 20px;
    left: 5%;
    //background-color: #817f7f5a;
    background-color: rgba(14, 14, 14, 0.4);
    box-sizing: border-box;
    color: rgb(233, 231, 231);

    .controlBar1_wt{
      //background-color: rgba(141, 11, 11, 0.35);
      width: 100%;
      height: 100%;

      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;

      .btn-left_wt{
        width: 80%;
        //background-color: #8ef8e7;
        display: flex;
        align-items: center;
        .progressVol_wt{
          width: 35px;
          height: 100px;
          margin-bottom: 20px;
          //background-color: #c80000;
        }
      }

      .btn-right_wt{
        width: 20%;
        //background-color: #0b54dc;
        display: flex;
        flex-direction: row-reverse;
        align-items: center;
      }

      .btn-i_wt{
        margin-left: 5px;
        cursor: pointer;
      }
    }
  }


}
</style>

/**
"视频播放":video.play();
"视频暂停播放":video.pause();
"视频地址":video.currentSrc;
"视频总时长":video.duration;
"视频播放速率":video.playbackRate;
"是否暂停":video.paused;
"是否结束":video.ended;
"是否静音":video.muted;
"当前播放时间": video.currentTime;
"当前缓冲量":video.buffered.end(0);
"当前音量":video.volume

src: 指定视频文件的URL地址。
controls: 控制视频播放器的控制条是否显示。
autoplay: 设置视频是否自动播放。
loop: 设置视频是否循环播放。
muted: 设置视频是否静音。
poster: 设置视频封面图片的URL地址。
currentTime: 获取或设置当前视频播放的时间。
duration: 获取视频的总时长。
play(): 开始播放视频。
pause(): 暂停视频播放。
preload: 指定视频文件的预加载行为，可以设置为"auto"、“metadata”、“none”。
paused: 返回一个布尔值，表示当前视频是否暂停播放。
volume: 设置视频的音量大小。
fullScreen: 视频全屏显示。
ended: 事件在视频播放结束时触发。
buffered: 返回一个TimeRanges对象，用来表示视频已经加载的缓冲范围。
played: 返回一个TimeRanges对象，用来表示视频已经播放的时间范围。
seekable: 返回一个TimeRanges对象，用来表示视频可以被快进的时间范围。
currentSrc: 获取当前视频播放的URL地址。
*/
